//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.yboot.starter.mybatis.core.handle;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private static final Logger log = LoggerFactory.getLogger(MybatisPlusMetaObjectHandler.class);
    private final List<InnerMetaObjectHandler> innerMetaObjectHandlers;

    public MybatisPlusMetaObjectHandler(List<InnerMetaObjectHandler> innerMetaObjectHandlers) {
        this.innerMetaObjectHandlers = innerMetaObjectHandlers;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (!CollectionUtils.isEmpty(this.innerMetaObjectHandlers)) {
            this.fillField(metaObject, false);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (!CollectionUtils.isEmpty(this.innerMetaObjectHandlers)) {
            this.fillField(metaObject, true);
        }
    }

    private void fillField(MetaObject metaObject, boolean update) {
        TableInfo tableInfo = this.findTableInfo(metaObject);
        for (TableFieldInfo tableFieldInfo : tableInfo.getFieldList()) {
            String column;
            Object fieldValue;
            String camelCase;
            if (tableFieldInfo.isWithInsertFill() && !update) {
                column = tableFieldInfo.getColumn();
                fieldValue = this.findFieldValue(column);
                camelCase = StrUtil.toCamelCase(column);
                this.setFieldValByName(camelCase, fieldValue, metaObject);
            }

            if (tableFieldInfo.isWithUpdateFill() && update) {
                column = tableFieldInfo.getColumn();
                fieldValue = this.findFieldValue(column);
                camelCase = StrUtil.toCamelCase(column);
                this.setFieldValByName(camelCase, fieldValue, metaObject);
            }
        }
    }

    private Object findFieldValue(String columnName) {
        Object fieldValue = null;
        for (InnerMetaObjectHandler objectHandler : this.innerMetaObjectHandlers) {
            fieldValue = objectHandler.getFieldValue(columnName);
        }
        return fieldValue;
    }
}
